
package com.dotools.utils;

import java.lang.ref.WeakReference;

import android.widget.Toast;

import com.dotools.debug.LOG;
import com.dotools.thread.ThreadPool;

public class ToastUtil {
    static WeakReference<Toast> sLastToast = null;

    public static void show(final String content, final int duration) {
        Runnable runnable  = new Runnable() {
            @Override
            public void run() {
                Toast last = sLastToast == null ? null : sLastToast.get();
                if (last != null) {
                    last.cancel();
                    LOG.logI("cancelling old toast: " + last);
                    sLastToast = null;
                }

                Toast current = Toast.makeText(Utilities.getApplicationContext(), content, duration);
                sLastToast = new WeakReference<Toast>(current);
                current.show();
            }
        };
        if (ThreadUtils.isUiThread()) {
            runnable.run();
        } else {
            ThreadPool.runOnUi(runnable);
        }
    }

    public static void show(final int contentRes, final int duration) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                Toast last = sLastToast == null ? null : sLastToast.get();
                if (last != null) {
                    last.cancel();
                    LOG.logI("cancelling old toast: " + last);
                    sLastToast = null;
                }

                Toast current = Toast.makeText(Utilities.getApplicationContext(), contentRes, duration);
                sLastToast = new WeakReference<Toast>(current);
                current.show();
            }
        };
        if (ThreadUtils.isUiThread()) {
            runnable.run();
        } else {
            ThreadPool.runOnUi(runnable);
        }
    }
}
